package com.getpebble.android.common.model;

import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.net.Uri;
import android.os.RemoteException;
import android.text.TextUtils;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblContentProviderUtil;
import com.getpebble.android.common.model.PblDataModel.Column;
import com.getpebble.android.common.model.PblDataModel.Column.Type;
import com.getpebble.android.util.SQLUtil;
import com.google.common.collect.ImmutableList;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class PblInstalledAppDataModel extends PblDataModel {
    public static final Uri TABLE_URI = PblContentProviderUtil.getTableUri("installed_apps");
    public static final String TAG = PblInstalledAppDataModel.class.getSimpleName();

    public PblInstalledAppDataModel() throws IllegalArgumentException {
        super("installed_apps");
        addColumn(new Column(Type.STRING, "device_address"));
        addColumn(new Column(Type.STRING, "uuid"));
        addColumn(new Column(Type.STRING, "app_name"));
        addColumn(new Column(Type.STRING, "company_name"));
        addColumn(new Column(Type.INTEGER, "install_id"));
        addColumn(new Column(Type.INTEGER, "bank_number"));
        addColumn(new Column(Type.STRING, "version"));
        addColumn(new Column(Type.INTEGER, "flags"));
        addColumn(new Column(Type.STRING, "capabilities"));
    }

    public String getCreateTableCommand() {
        return SQLUtil.getCreateTableCommandWithUniqueConstraint(super.getCreateTableCommand(), ImmutableList.of(ImmutableList.of("device_address", "uuid"), ImmutableList.of("device_address", "bank_number"), ImmutableList.of("device_address", "app_name", "company_name", "version")));
    }

    public static synchronized Cursor fetchInstalledApps(ContentResolver contentResolver, PblDevice device) {
        Cursor query;
        synchronized (PblInstalledAppDataModel.class) {
            String[] selectionArgs = new String[]{device.getAddress()};
            ContentResolver contentResolver2 = contentResolver;
            query = contentResolver2.query(TABLE_URI, null, "device_address = ?", selectionArgs, null);
        }
        return query;
    }

    public static void catInstalledAppsToStream(ContentResolver contentResolver, PrintStream printStream) {
        Cursor cursor = contentResolver.query(TABLE_URI, null, null, null, "device_address ASC");
        DatabaseUtils.dumpCursor(cursor, printStream);
        if (cursor != null) {
            cursor.close();
        }
    }

    public static synchronized boolean deleteApps(ContentResolver contentResolver, List<Integer> appIds) {
        boolean z;
        synchronized (PblInstalledAppDataModel.class) {
            int rowsDeleted = contentResolver.delete(TABLE_URI, "_id IN (" + TextUtils.join(", ", appIds) + ")", null);
            Trace.debug(TAG, "Deleted " + rowsDeleted + " rows.");
            z = rowsDeleted != 0;
        }
        return z;
    }

    public static synchronized boolean insertApp(ContentResolver contentResolver, ContentValues contentValues) {
        boolean z;
        synchronized (PblInstalledAppDataModel.class) {
            z = contentResolver.insert(TABLE_URI, contentValues) != null;
        }
        return z;
    }

    public static synchronized int removeApp(ContentResolver contentResolver, PblDevice device, UUID uuid) {
        int delete;
        synchronized (PblInstalledAppDataModel.class) {
            String[] selectionArgs = new String[]{uuid.toString(), device.getAddress()};
            delete = contentResolver.delete(TABLE_URI, "uuid = ? AND device_address = ?", selectionArgs);
        }
        return delete;
    }

    public static synchronized boolean updateApps(ContentResolver contentResolver, List<ContentValues> contentValueList) {
        boolean z;
        synchronized (PblInstalledAppDataModel.class) {
            if (contentValueList.isEmpty()) {
                z = true;
            } else {
                ArrayList<ContentProviderOperation> operations = new ArrayList();
                for (ContentValues contentValues : contentValueList) {
                    operations.add(ContentProviderOperation.newUpdate(TABLE_URI).withSelection("_id = ?", new String[]{contentValues.getAsInteger("_id").toString()}).withValues((ContentValues) i$.next()).build());
                }
                try {
                    z = true;
                    for (ContentProviderResult result : contentResolver.applyBatch("com.getpebble.android.internal.provider", operations)) {
                        z = z && result.count.intValue() == 1;
                    }
                } catch (RemoteException e) {
                    Trace.error(TAG, "Failed to update installed apps.", e);
                    z = false;
                    return z;
                } catch (OperationApplicationException e2) {
                    Trace.error(TAG, "Failed to update installed apps.", e2);
                    z = false;
                    return z;
                }
            }
        }
        return z;
    }

    public static synchronized int fetchBankForUuid(ContentResolver contentResolver, PblDevice device, UUID uuid) {
        int bankNumber;
        synchronized (PblInstalledAppDataModel.class) {
            bankNumber = -1;
            String[] projection = new String[]{"bank_number"};
            String[] selectArgs = new String[]{device.getAddress(), uuid.toString()};
            ContentResolver contentResolver2 = contentResolver;
            Cursor cursor = contentResolver2.query(TABLE_URI, projection, "device_address = ? AND uuid = ?", selectArgs, null);
            if (cursor.moveToNext()) {
                bankNumber = cursor.getInt(cursor.getColumnIndex("bank_number"));
            }
            cursor.close();
        }
        return bankNumber;
    }

    public static synchronized int fetchNextEmptyBank(ContentResolver contentResolver, PblDevice device) {
        int index;
        synchronized (PblInstalledAppDataModel.class) {
            String[] projection = new String[]{"bank_number"};
            String[] selectArgs = new String[]{device.getAddress()};
            ContentResolver contentResolver2 = contentResolver;
            Cursor usedBankNumberCursor = contentResolver2.query(TABLE_URI, projection, "device_address = ?", selectArgs, "bank_number ASC");
            index = 0;
            while (usedBankNumberCursor.moveToNext() && usedBankNumberCursor.getInt(usedBankNumberCursor.getColumnIndex("bank_number")) == index) {
                index++;
            }
            usedBankNumberCursor.close();
            if (index >= 8) {
                index = -1;
            }
        }
        return index;
    }
}
